<template>
  <div class="groupDiv">
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{alertText}}</alert>
    </div>
    <div v-transfer-dom>
      <confirm
        :title="titleOfDelOrReplyConfirm"
        :hide-on-blur="true"
        v-model="isShowActionOnCommentConfirm"
        @on-confirm="clickDelOrReplyConfirm"
      ></confirm>
    </div>
    <!-- 添加评论的弹出框 -->
    <TextInput :isShowCommentConfirm.sync="isShowCommentConfirm"></TextInput>

    <!--循环显示获取的日报-->
    <div class="wrapper">
      <div class="scroll-content">
        <div
          class="chatDiv scroll-content"
          v-for="(item,index) in reportContentProf"
          :key="index"
          style="margin-bottom: 20px">
          <div
            style="display:inline-block; width:50px; height:auto; padding:0; text-align:center;
            margin-left:5px; border:0px; background-color:rgb(237,237,237);">
            <!-- 设置点击头像进入分组管理，此功能仅在单人模式下生效 -->
            <img class="myHeadIcon" v-bind:src="item.avatar" @click="showRepoOfThisStudent(item)" />
            <br />
            <label class="name">{{item.userName}}</label>
            <br />
            <span class="place">{{item.place}}</span>
          </div>
          <!--      方框前的三角形-->
          <span class="triangle"></span>
          <div class="content">
            <div style="max-height: 25px;background-color: #ededed;margin-top: -3px;">
              <img
                src="~static/img/put_time.png"
                height="13"
                width="13"
                alt="提交"
                style="font-size:12px;color:gray;color: rgb(191,191,191);"
              />
              <span
                style="font-size:14px;color:gray;"
              >{{item.insertTime[0]}} {{item.insertTime[1]}}&nbsp;&nbsp;</span>
              <span style="font-size:12px;color:gray;color: rgb(191,191,191);">学习</span>
              <span style="font-size:14px;color:gray;">{{item.timeCostStudy}}h</span>
              <span style="font-size:12px;color:gray;color: rgb(191,191,191);">有效产出</span>
              <span style="font-size:14px;color:gray;">{{item.timeCostOutput}}h</span>
            </div>
            <span style="font-size:14px;color:#C1C1C1;float:left;">日报日期：{{item.date.slice(5,10)}}</span>
            <br v-if="!isShowPopover(item,2)" />
            <div class="content-detail">
              <popover placement="left" v-if="isShowPopover(item,2)">
                <div
                  slot="content"
                  class="popover-demo-content"
                  style="padding: 8px;border-radius: 5px"
                >
                  <span
                    @click="modifyReport(item)"
                    style="line-height:30px; padding:8px; color:white"
                  >修&nbsp;改</span>
                  <br />
                  <span
                    @click="deleteReport(item)"
                    style="line-height:30px;padding:8px; color:white"
                  >删&nbsp;除</span>
                </div>
                <button class="btn btn-default">
                  <i class="fa fa-ellipsis-v"></i>
                </button>
              </popover>

              <span v-for="(item_in,index) in item.activities" :key="index">
                <div style="margin: 3px">
                  <span
                    class="tag"
                    style="margin-left: 1px;margin-bottom: 5px;margin-top:5px;letter-spacing:0.5px;"
                  >{{item_in.typeContent}}</span>
                  <span
                    style="font-size:small;color: rgb(191,191,191);"
                  >{{item_in.startTime.slice(0,5)}}--{{item_in.endTime.slice(0,5)}}</span>
                  <span style="color:gray">（{{item_in.timeCost}}h）</span>
                  <br />
                  <span
                    style="color: grey;font-size: small;font-family: '微软雅黑';letter-spacing:0.5px;word-wrap:break-word;white-space:normal;"
                  >{{item_in.content}}</span>
                  <br />
                </div>
              </span>
              <div style="margin-left:5px; margin-right:5px; margin-bottom:5px">
                <span v-if="item.impression!=='' && item.impression!==null">感想：{{item.impression}}</span>
              </div>
              <div v-if="item.target" style="margin: 3px">
                <span
                  class="tag"
                  style="margin-bottom: 5px;margin-top:10px;letter-spacing:0.5px;"
                >明日计划:</span>
                <span
                  style="color: grey;font-size: small;font-family: '微软雅黑';letter-spacing:0.5px;word-wrap:break-word;white-space:normal;"
                >{{item.target}}</span>
              </div>
              <div style="margin-left: 85%; padding-right:20px;">
                <img
                  src="~static/img/comment.png"
                  height="25"
                  width="25"
                  @click="clickCommentButton(item)"
                  alt="评论"
                />
                <!--          <i class="fa fa-commenting-o fa-2x" @click="clickCommentButton(item)"></i>-->
              </div>
            </div>
            <br />

            <div v-for="(comment, index) in item.commentList" :key="index">
              <div
                style="margin-left:5px; margin-right:5px; margin-bottom:5px; font-size:13px"
                v-show="comment.groupId === currentGroupId"
                @click="clickCommentText(comment)"
              >
                <span style="color:rgb(70,83,109); font-weight:bold;color: #3D59AB">{{comment.userName}}</span>
                <span v-if="comment.replyUserId !== null">回复</span>
                <span
                  v-if="comment.replyUserId !== null"
                  style="color:rgb(70,83,109); font-weight:bold;color: #3D59AB"
                >{{comment.replyUserName}}</span>
                <span style="font-size: small;">:{{comment.content}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div style="text-algin:center">
      <label style="color:rgba(100,100,100,0.7)" @click="getMoreReports()">—————— 点击加载更多 ——————</label>
    </div>
    <div style="height:40px" />
  </div>
</template>

<script>
import { Popover, Confirm } from "vux";
import { mapState } from "Vuex";
import report from "api/report";
import comment from "api/comment";
import TextInput from "components/TextInput/TextInput.vue";
import common from "utilMethods/common.js";
import BScroll from 'better-scroll'
const deleteHint = "是否删除此条评价？";
const replyHint = "是否回复此条评价？";

export default {
  name: "dayView",
  data() {
    return {
      alertText: "", // 验证提示框的文本
      isShowAlert: false, // 是否显示验证提示,
      isShowCommentConfirm: false,
      titleOfDelOrReplyConfirm: "",
      isShowActionOnCommentConfirm: false,
      commentSelected: {},
      countClickMoreReports: 1
    };
  },
  mounted() {
    new BScroll( document.querySelector('.wrapper'),{
      click:true
     })
    this.countClickMoreReports = 1;
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    ...mapState([
      "reportContentProf",
      "reportListQueryParams",
      "currentGroupId"
    ])
  },
  watch:{
  },
  components: {
    Popover,
    Confirm,
    TextInput
  },
  methods: {
    isShowPopover(item, some) {
      if (
        item.userId === this.userInfo.userId &&
        this.compareTwoDay(item.date, some)
      ) {
        return true;
      } else {
        return false;
      }
    },
    //判断该汇报日期是否超过了some天，如超过返回false，不允许进行修改
    compareTwoDay(date, some) {
      // 2020-03-03
      let now = Date.now(); //当前时间的时间戳
      let strYear = date.slice(0, 4);
      let strMonth = date.slice(5, 7);
      let strDay = date.slice(8);
      let day = strMonth + "/" + strDay + "/" + strYear;
      var dateTime = new Date(day).getTime(); //汇报日期的时间戳
      if (now - dateTime <= 1000 * 60 * 60 * 24 * some) {
        return true;
      } else {
        return false;
      }
    },
    back() {
      this.$router.go(-1);
    },
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    async deleteReport(item) {
      const result = await report.deleteReport(item.reportId);
      if (result.code === 0) {
        this.showAlert(result.message);
      } else {
        this.showAlert("成功删除" + item.date + "的日报");
      }
    },
    modifyReport(item) {
      this.changeColor = true;
      this.temp = item;
      this.$router.push({
        name: "addReport",
        params: { type: "日报", isReallyModifyContentDay: true }
      });
      this.$store.commit("stageModifyContentDay", item);
    },
    showRepoOfThisStudent(item) {
      this.$emit("func", item.userId);
    },
    // 评论相关代码
    clickCommentButton(item) {
      console.log("reportCommented");
      console.log(item);
      this.$store.commit("stageReportCommented", item);
      let commentType = "评价";
      this.$store.commit("stageCommentType", commentType);
      this.isShowCommentConfirm = true;
    },
    clickCommentText(comment) {
      console.log("commentSelected");
      console.log(comment);
      this.commentSelected = comment;
      this.$store.commit("stageCommentSelected", comment);
      if (
        this.userInfo.userId === comment.userId ||
        this.userInfo.userId === comment.replyUserId
      ) {
        this.titleOfDelOrReplyConfirm = deleteHint;
      } else {
        this.titleOfDelOrReplyConfirm = replyHint;
      }
      this.isShowActionOnCommentConfirm = true;
    },
    clickDelOrReplyConfirm() {
      if (deleteHint === this.titleOfDelOrReplyConfirm) {
        this.deleteComment();
      } else {
        let commentType = "回复";
        this.$store.commit("stageCommentType", commentType);
        this.isShowCommentConfirm = true;
      }
    },
    async deleteComment() {
      const result = await comment.getDeleteComment(
        this.commentSelected.commentId
      );
      if (1 === result.code) {
        // 更新删除了评价的日报
        const res = await report.getReportsByGroupId(
          this.reportListQueryParams
        );
        this.$store.dispatch("getReportContentProf", res.data);
        this.showAlert(result.data);
        setTimeout(this.closeTip, 1500);
      } else {
        this.showAlert("删除失败，请稍后再试");
        setTimeout(this.closeTip, 1500);
      }
    },
    async getMoreReports() {
      this.countClickMoreReports += 1;
      console.log(this.countClickMoreReports);
      let moreReportsParams = this.reportListQueryParams;
      moreReportsParams.end = this.reportListQueryParams.start;
      moreReportsParams.start = common.setDayCompareWithToday(
        -7 * this.countClickMoreReports
      );
      const result = await report.getReportsByGroupId(moreReportsParams);
      console.log(result.data);
      let oldReportContent = this.reportContentProf;
      console.log(oldReportContent);
      this.addressReportContentProf(result.data, oldReportContent);
      console.log(this.reportContentProf);
    },
    addressReportContentProf(reportContentProf, oldReportContent) {
      if (reportContentProf.length !== 0) {
        reportContentProf.forEach(element => {
          if (element.insertTime === null) {
            element.insertTime = element.date + "T" + " ";
          }
          element.insertTime = common
            .transferTimeString(element.insertTime)
            .split("T");
          let timeCostOutput = 0;
          let timeCostStudy = 0;
          element.activities.forEach(activity => {
            let start, end;
            if (activity.endTime !== null)
              end =
                Number(activity.endTime.slice(0, 2)) +
                Number(activity.endTime.slice(3, 5)) / 60;
            if (activity.startTime !== null)
              start =
                Number(activity.startTime.slice(0, 2)) +
                Number(activity.startTime.slice(3, 5)) / 60;
            let timeCost = (end - start + "").slice(0, 3);
            activity["timeCost"] = timeCost;
            // -2：休息；-1：个人疫情汇报；0：学习
            if (activity.type !== -2 && activity.type !== -1) {
              if (
                activity.typeContent.indexOf("学习") !== -1 ||
                activity.typeContent.indexOf("课") !== -1 ||
                activity.typeContent.indexOf("组会") !== -1
              ) {
                timeCostStudy += Number(timeCost);
              } else {
                timeCostOutput += Number(timeCost);
              }
            }
          });
          element["timeCostOutput"] = (timeCostOutput + "").slice(0, 4);
          element["timeCostStudy"] = (timeCostStudy + "").slice(0, 4);
        });
        let newReportContentProf = oldReportContent.concat(reportContentProf);
        console.log(newReportContentProf);
        this.$store.commit("stageReportContentProf", newReportContentProf);
      }
    }
  }
};
</script>

<style lang="less">
.wrapper{
  height: 800px;
}
.button {
  right: 2rem;
  bottom: 5rem;
  padding: 30px;
  background-color: rgba(152, 252, 101, 0.6);
  border-radius: 100%;
  border-color: rgba(152, 252, 101, 0.6);
  position: fixed;
  z-index: 999;
}
</style>
